'use strict';

module.exports = app => {
  class StudentController extends app.Controller {
    async list (ctx) {
      let results = await ctx.app.model.student.doc.find().limit(10)

      let total = await ctx.app.model.student.doc.count()

      if (!results || !results.length) {
        ctx.helper.rest.resp({
          ctx,
          code: 1,
          error: 'Not Found'
        })
        return
      }

      ctx.helper.rest.resp({
        ctx,
        code: 0,
        data: {
          total,
          list: results.map(x => x.toObject({
            virtuals: true,
            transform: function (doc, ret, options) {
              // ret.id = ret._id
              delete ret._id
              return ret
            }
          }))
        }
      })
    }

    async uer_bulk_transiaction (ctx) {
      let results = await ctx.app.model.student.doc.find().limit()

      if (!results || !results.length) {
        ctx.helper.rest.resp({
          ctx,
          code: 1,
          error: 'No Student Found.'
        })
        return
      }

      let userMap = new Map()
      for (let student of results) {
        userMap.set(student.no, student)
      }

      let userList = []
      // console.log(Object.keys(ctx.app.mongoose));
      userMap.forEach((student) => {
        let user = new ctx.app.model.user.doc({
          username: student.no,
          user_type: 'student',
          nick: student.name,
          user_comment: {
            student_id: student.id // ctx.app.mongoose.Schema.Types.ObjectId(student.id)
          },
          password: '123456'
        }, {virtuals: true, transform: (doc, ret, options) => {
          delete ret._id
          ret.password = doc.hash_password
          return ret
        }})
        user.password = user.hash_password

        userList.push(user.toJSON())
      })
      // userList = Array.from(userMap.values())

      let res = await ctx.app.model.user.doc.insertMany(userList).catch(ctx.helper.genAppError({ctx}))

      if (ctx.helper.abortOnError({
        ctx,
        error: res,
        code: res.code,
        message: 'fail to transfer students entity to users'
      })) return

      ctx.helper.rest.resp({
        ctx,
        code: 0,
        data: {
          list: userList
        }
      })
    }
  }

  return StudentController
}
